package com.zlb.configuration;

import com.zlb.domain.User;
import com.zlb.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class DbShiroRealm extends AuthorizingRealm {

  private static final String encryptSalt = "F12839WhsnnEV$#23b";

  @Autowired
  private UserService userService;

  @Override
  public boolean supports(AuthenticationToken token) {
    return token instanceof UsernamePasswordToken;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {
    UsernamePasswordToken userpasswordToken = (UsernamePasswordToken) token;
    String username = userpasswordToken.getUsername();
    User user = userService.getUserInfo(username);
    if (user == null) {
      throw new AuthenticationException("用户名或者密码错误");
    }
    return new SimpleAuthenticationInfo(user, user.getPassword(),
        ByteSource.Util.bytes(encryptSalt), "dbRealm");
  }


  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    User user = (User) principals.getPrimaryPrincipal();
    java.util.List<String> roles = user.getRoles();
    if (roles == null) {
      roles = userService.getUserRoles(user.getUserId());
      user.setRoles(roles);
    }
    if (roles != null) {
      simpleAuthorizationInfo.addRoles(roles);
    }

    return simpleAuthorizationInfo;
  }


}
